package MyFitnessPlate.TestApplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import MyFitnessPlate.DataSet.ParsedExerciseDataSet;
import MyFitnessPlate.Handler.ExerciseHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.DatePicker.OnDateChangedListener;

public class ExerciseActivity extends Activity {
	private int initialDay;
	private int initialMonth;
	private int initialYear;
	
	private ArrayList<Integer> exerciseEntryIdList = new ArrayList<Integer>();
	private ArrayList<ParsedExerciseDataSet> exerciseList = new ArrayList<ParsedExerciseDataSet>();
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exercise_screen);
        
        final DatePicker datePicker = (DatePicker) findViewById(R.id.exercise_date_picker);
        final ListView listView = (ListView) findViewById(R.id.exercise_list_view);
        final Button addButton = (Button) findViewById(R.id.add_exercise_button);
        
      //Set the current date.
        Date date = new Date();
        datePicker.init(date.getYear()+1900,date.getMonth(), date.getDate(),new OnDateChangedListener(){
        	public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
        	    // Notify the user.
        		if(initialDay != datePicker.getDayOfMonth() ||
				   initialMonth != datePicker.getMonth() ||
				   initialYear != datePicker.getYear()){
					//This will load the entries for a specific date.
					setDateToSelection(datePicker.getDayOfMonth(), datePicker.getMonth(), datePicker.getYear());
					//Now load the feed					
					loadExerciseEntries();
					loadFeed(listView);
				}
        	}
        });
     // Get the day, month, and year from the Date Picker for the URL...
        setDateToSelection(datePicker.getDayOfMonth(), datePicker.getMonth(), datePicker.getYear());
             
        loadExerciseEntries();
		loadFeed(listView);
        
		  //Allow the child elements to be selectable.
        //When the elements are clicked, they will be able to allow a user to delete an item on the list.
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
               public void onItemClick(AdapterView<?> adapterView, View view,int arg2, long arg3) {
            	   final int selectedElement = arg2;
            	   DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            		    public void onClick(DialogInterface dialog, int which) {
            		        switch (which){
            		        case DialogInterface.BUTTON_POSITIVE:
            		            //"yes" action - This will start the method to delete the selected entry-id
            		        	// Once this is done, the food entries will be loaded and the feed will be loaded.
            		        	//Send a message to delete the item on the list.
            		        	try {
            		        		URL url = new URL("http://myfitnessplate.com/api/delete-exercise-entry/id/"+exerciseEntryIdList.get(selectedElement).intValue()+"/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
            		        		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            		        		in.close();
            		        		//Notify them of the 
            		        		final AlertDialog alertDialog = new AlertDialog.Builder(ExerciseActivity.this).create();
                                	alertDialog.setTitle("Deleted");
                                	alertDialog.setMessage("The item has been deleted from the list.");
                                	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                		public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); }
                                	});
                                	alertDialog.show();
            		        	} catch (MalformedURLException e) {
            		        		handleError("URL error", "URL is incorrect", e);
            		        	} catch (IOException e) {
            		        		handleError("IO error", "Check files", e);
            		        	}
            		        	
            		        	loadExerciseEntries();
            		        	loadFeed(listView);
            		        	break;
            		        case DialogInterface.BUTTON_NEGATIVE:
            		            //"no" action - do nothing.
            		        	break;
            		        }
            		    }
            		};
            		final AlertDialog.Builder builder = new AlertDialog.Builder(ExerciseActivity.this);
            		builder.setMessage("Delete this entry?").setPositiveButton("Yes", dialogClickListener)
            		    .setNegativeButton("No", dialogClickListener).show();
               }
           }
        );
		
        //Takes you to the add exercise page.
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	setDateToSelection(datePicker.getDayOfMonth(), datePicker.getMonth(), datePicker.getYear());
            	
            	String userName = getParent().getIntent().getExtras().getString("userName");
            	//Sends user to add their exercise from the ExerciseAddScreen. Sends the current date.
            	Bundle b = new Bundle();
            	b.putInt("Day", initialDay);
            	b.putInt("Month",initialMonth);
            	b.putInt("Year", initialYear);
            	b.putString("User", userName);
            	
            	Intent myIntent = new Intent("MyFitnessPlate.TestApplication.ExerciseAddActivity.STARTINGPOINT");
            	myIntent.putExtras(b);
				startActivity(myIntent);
            }
        });    
    }
	
	/**
     * This method allows the food entries to be loaded from the web site.
     */
    private void loadExerciseEntries(){
    	try {
    		String userName = getParent().getIntent().getExtras().getString("userName");
			URL url = new URL("http://myfitnessplate.com/api/fetch-exercise-log/username/" + userName +
							  "/day/"+formatDayMonth(initialDay)+"/month/"+formatDayMonth(initialMonth)+
							  "/year/"+initialYear+"/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader */
			ExerciseHandler myExerciseHandler = new ExerciseHandler();
			xr.setContentHandler(myExerciseHandler);
			/* Parse the xml-data from our URL. */
			xr.parse(new InputSource(url.openStream()));
			/* Parsing has finished. */
			/* Our ExampleHandler now provides the parsed data to us. */
			exerciseList = myExerciseHandler.getParsedData();
		} catch (MalformedURLException e) {
			handleError("URL error", "URL is incorrect", e);
		} catch (ParserConfigurationException e) {
			handleError("Parser error", "Check the parser", e);
		} catch (SAXException e) {
			handleError("SAX error", "The SAX parser failed", e);
		} catch (IOException e) {
			handleError("IO error", "Check files", e);
		} finally {}
	}
	
	private void loadFeed(ListView listView){
    	try{
	    	//Set up a new list to display the food items.
    		List<String> display = new ArrayList<String>(0);
	    	//Clear the food entry id list so only the new entries will be included.
    		//This is for deleting entries.
    		exerciseEntryIdList.clear();
	    	for (ParsedExerciseDataSet peds : exerciseList){
	    		if(peds != null ){
	    			display.add(peds.toString());
	    			exerciseEntryIdList.add(peds.getEntry_id());
	    		}
	    	}
	    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.exerciseitem, display);
	    	listView.setAdapter(adapter);
    	} catch (Throwable t){
    		Log.e("Exercise item",t.getMessage(),t);
    	}
    }
	
	private String formatDayMonth(int dayOrMonth){
	   	if(dayOrMonth < 10){
	   		return "0"+dayOrMonth;
	   	} else {
	   		return ""+dayOrMonth;
	   	}
	}
	
	private void setDateToSelection(int day, int month, int year){
    	initialDay = day; //Day
        initialMonth = month+1; //Month
        initialYear = year; //year
    }
	private void handleError(String tag, String message, Exception e) {
		Log.d(tag, message);
		e.printStackTrace();
	}
	
	public void onResume(){
		super.onResume();
		//Update exercise information and the feed.
		final ListView listView = (ListView) findViewById(R.id.exercise_list_view);
		
		loadExerciseEntries();
		loadFeed(listView);
	}
	
	public void onRestart(){
		super.onRestart();
		onResume();
	}
}